package com.scilvet.reportcomposer.report;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.scilvet.reportcomposer.node.Node;
import com.scilvet.reportcomposer.report.parser.ParseException;

public class ReportStore implements Iterable<Report> {
	
	private Map<String, Report> reportList = new HashMap<String, Report>();
	
	public ReportLine createReportLine(Integer lineNumber, String description, Node expression) {
		
		if (lineNumber == null || description == null || expression == null) {
			throw new IllegalArgumentException("createLine called with null parameters");
		}
		
		return new ReportLine(lineNumber, description, expression);
	}
	
	public TitleLine createTitleLine(Integer lineNumber, String title) {
		
		if (lineNumber == null || title == null) {
			throw new IllegalArgumentException("createTitleLine called with null parameters");
		}
		
		return new TitleLine(lineNumber, title);
	}
	
	public void addLine(Report report, Line line) {
		
		if (report == null || line == null) {
			throw new IllegalArgumentException("addLine caled with null parameters");
		}
		
		report.addLine(line);
	}
	
	public Report createReport(String name) throws ParseException {
		
		if (name == null) {
			throw new IllegalArgumentException("createReport called with null parameters");
		}
		
		if (reportList.containsKey(name)) {
			throw new ParseException("Duplicate report " + name);
		}
		
		Report report = new Report(name);
		reportList.put(name, report);
		
		return report;
	}
	
	public boolean hasLine(String reportName, Integer lineNumber) {
		
		if (!reportList.containsKey(reportName)) {
			return false;
		}
		
		Report report = reportList.get(reportName);
		return report.containsLine(lineNumber);
	}
	
	public Line getLine(String reportName, Integer lineNumber) {
		
		if (reportName == null || lineNumber == null) {
			throw new IllegalArgumentException("getLine called with null parameters");
		}
		
		Report report = reportList.get(reportName);
		if (report == null) {
			throw new IllegalArgumentException("getLine: report " + reportName + " not found");
		}
		
		Line line = report.getLine(lineNumber);
		if (line == null) {
			throw new IllegalArgumentException("getLine: line " + lineNumber + " not found in " + reportName);
		}
		
		return line;
	}

	@Override
	public Iterator<Report> iterator() {
		return reportList.values().iterator();
	}
	
}
